<template>
  <div class="page">
    <div class="handlePart">
      <el-form :inline="true" :model="form">
        <el-form-item label="关键字">
          <el-tooltip class="tips" content="请输入取水口或取水户的编码或名称" placement="top-start">
            <i class="el-icon-info"></i>
          </el-tooltip>
          <el-input size="small" v-model="form.keywords" style="width: 220px;" placeholder="请输入关键字"
            clearable></el-input>
        </el-form-item>
        <el-form-item label="行政分区：">
          <el-cascader  ref="areaCodeRef"   v-model="areaChecked" size="small" style="width: 150px;"
            :props="{ expandTrigger: 'hover', label: 'name', value: 'areaCode', checkStrictly: true }" :options="areaTree" placeholder="请选择"
            clearable :show-all-levels="false" filterable @change="handleAreaCodeChange"></el-cascader>
        </el-form-item>
        <el-form-item label="流域分区：">
          <el-cascader ref="basinCodeRef" v-model="basinChecked" size="small" style="width: 150px;"
            :props="{expandTrigger: 'hover', label: 'name', value: 'basinCode', checkStrictly: true }" :options="basinOptions" placeholder="请选择"
            clearable :show-all-levels="false" filterable @change="handleBasinCodeChange"></el-cascader>
        </el-form-item>

        <el-form-item>
          <el-button size="small" type="warning" icon="el-icon-clear" @click="clear">清空</el-button>
        </el-form-item>
        <el-form-item>
          <el-button size="small" type="primary" icon="el-icon-search" @click="search">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button size="small" type="success" icon="el-icon-download" @click="exportExcel">数据导出</el-button>
        </el-form-item>
        <el-form-item style="float: right">
          <el-button size="small" type="primary" icon="el-icon-plus" @click="add">新增</el-button>
          <el-button size="small" type="danger" icon="el-icon-delete" @click="dels">删除</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="tablePart">
      <el-table id="table" ref="listTable" :data="list" :height="'calc(100vh - 290px)'" stripe style="width: 100%"
        @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column label="序号" type="index" align="center" width="55"></el-table-column>
        <el-table-column prop="ecNumSub" label="取水口编号" align="center"> </el-table-column>
        <el-table-column prop="name" label="取水口名称" align="center"> </el-table-column>
        <el-table-column prop="ecNum" label="取水户编码" align="center"> </el-table-column>
        <el-table-column prop="engName" label="取水户名称" align="center"> </el-table-column>
        <el-table-column prop="areaCode" label="行政分区" align="center" :formatter="areaFormatter"> </el-table-column>
        <el-table-column prop="basinCode" label="流域分区" align="center" :formatter="basinFormatter"> </el-table-column>
        <el-table-column prop="source" label="来源" align="center"> </el-table-column>
        <el-table-column prop="purpose" label="用途" align="center"> </el-table-column>
        <el-table-column prop="longitude" label="经度" width="100" align="center"> </el-table-column>
        <el-table-column prop="latitude" label="纬度" width="100" align="center"> </el-table-column>
        <el-table-column fixed="right" label="操作" align="center" width="160">
          <template slot-scope="scope">
            <el-button type="text" icon="el-icon-edit" title="编辑" @click="edit(scope.row)"></el-button>
            <el-button type="text" icon="el-icon-delete" title="删除" @click="del(scope.row)"></el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagePart">
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="page"
          :page-sizes="[10, 20, 30, 40, 50]" :page-size="size" layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>
    </div>
    <EditDialog ref="editDialogRef" @listInit="listInit" />
    <!-- <DetailDialog ref="detailDialogRef" /> -->
  </div>
</template>
<script>
import EditDialog from './editDialog.vue';
import SingleSelectCascader from '@/components/SingleSelectCascader.vue';
import { mapState } from "vuex";
// import DetailDialog from './detailDialog.vue';
export default {
  data() {
    return {
      form: {
        areaCode: 0,
        basinCode: 0,
        keywords: '',
        orderBy: ""
      },
      areaChecked: [],
      basinChecked: [],
      list: [],
      page: 1,
      size: 10,
      total: 0,
      selectList: []
      // basinOptions: [],
      // areaTree: []
    };
  },
  computed: {
    ...mapState(["areaTree", "basinOptions"]),
  },
  mounted() {
    this.listInit();
  },
  methods: {
    listInit() {
      if (this.areaChecked.length > 0) {
        this.form.areaCode = parseInt(this.areaChecked.slice(-1)[0])
      }
      if (this.basinChecked.length > 0) {
        this.form.basinCode = parseInt(this.basinChecked.slice(-1)[0])
      }
      let params = Object.assign({}, this.form, {
        size: this.size,
        page: this.page,
        orderBy: ""
      })
      this.$api.getWaterIntakeList(params).then((res) => {
        if (res && res.code == 200) {
          let data = res.data || {}
          this.total = data.total || 0
          this.list = data.list || []
        }
      })
    },
    // 查询
    search() {
      this.page = 1
      this.listInit()
    },
    clear() {
      this.areaChecked = []
      this.basinChecked = []
      Object.assign(this.form, this.$options.data().form)
      this.listInit()
    },
    async exportExcel() {
      let params = Object.assign({}, this.form, {
        size: 99999,
        page: 1,
        orderBy: ""
      })
      const allRes = await this.$api.getWaterIntakeList(params);
      if (allRes && allRes.code === 200) {
        const data = allRes.data.list || [];
        const arecode = "areaCode"
        const basinCode = "basinCode"
        
        // 处理导出数据
        const exportData = data.map(item => {
          // 在树形结构中查找县级节点及其父节点
          const findNodeWithParent = (tree, code) => {
            for (const node of tree) {
              if (node.areaCode === code) {
                return { node, parent: null };
              }
              if (node.children) {
                for (const child of node.children) {
                  if (child.areaCode === code) {
                    return { node: child, parent: node };
                  }
                  // 继续在子节点的children中查找
                  if (child.children) {
                    for (const grandChild of child.children) {
                      if (grandChild.areaCode === code) {
                        return { node: grandChild, parent: child };
                      }
                    }
                  }
                }
              }
            }
            return null;
          };

          // 在树形结构中查找节点的完整路径
          const findNodePath = (tree, code) => {
            const path = [];
            const find = (nodes, targetCode) => {
              for (const node of nodes) {
                if (node.basinCode === targetCode) {
                  path.push(node.name);
                  return true;
                }
                if (node.children) {
                  path.push(node.name);
                  if (find(node.children, targetCode)) {
                    return true;
                  }
                  path.pop();
                }
              }
              return false;
            };
            find(tree, code);
            return path;
          };

          // 获取市县信息
          const areaInfo = findNodeWithParent(this.areaTree, item.areaCode);
          let city = '', county = '';
          
          if (areaInfo) {
            const { node, parent } = areaInfo;
            if (parent) {
              // 如果找到父节点，说明当前节点是县级，父节点是市级
              city = parent.name || '';
              county = node.name || '';
            } else {
              // 如果没有父节点，说明当前节点是市级
              city = node.name || '';
            }
          }

          // 获取流域分区的完整路径
          const basinPath = findNodePath(this.basinOptions, item.basinCode);
          const formattedBasin = basinPath.length > 0 ? basinPath.join('/') : '***';

          return {
            ecNumSub: item.ecNumSub,         // 取水口编号
            name: item.name,                  // 取水口名称
            ecNum: item.ecNum,               // 取水户编码
            engName: item.engName,           // 取水户名称
            city,                            // 市
            county,                          // 县
            basinCode: formattedBasin,       // 流域分区（完整路径）
            surfaceAmount: item.surfaceAmount || 0,  // 许可地表水量
            source: item.source,             // 来源
            purpose: item.purpose,           // 用途
            longitude: item.longitude,       // 经度
            latitude: item.latitude          // 纬度
          };
        });

        // 创建一个临时表格对象，包含所需的列信息
        const tempTableRef = {
          columns: [
            { label: '取水口编号', property: 'ecNumSub' },
            { label: '取水口名称', property: 'name' },
            { label: '取水户编码', property: 'ecNum' },
            { label: '取水户名称', property: 'engName' },
            { label: '市', property: 'city' },
            { label: '县', property: 'county' },
            { label: '许可地表水量(万m³)', property: 'surfaceAmount' },
            { label: '流域分区', property: 'basinCode' },
            { label: '来源', property: 'source' },
            { label: '用途', property: 'purpose' },
            { label: '经度', property: 'longitude' },
            { label: '纬度', property: 'latitude' }
          ],
          $message: this.$message  // 添加消息提示方法
        };

        this.$exportExcel(exportData, tempTableRef, "取水口管理");
      } else {
        this.$message.error('获取数据失败');
      }
    },
    // 新增
    add() {
      this.$refs.editDialogRef.showModal('add');
    },
    // 编辑
    edit(row) {
      this.$refs.editDialogRef.showModal('edit', row);
    },
    // 配置
    config(row) {
      // this.$refs.detailDialogRef.showModal(row);
    },
    // 删除
    del(row) {
      this.$confirm('数据删除后将无法恢复，确认删除吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$api.delWaterIntake([row.id]).then(res => {
          if (res && res.code == 200) {
            this.$notify.success({
              title: '成功',
              message: '删除成功!'
            });
            this.listInit()
          }
        })
      }).catch(() => { });
    },
    // 批量删除
    dels() {
      if (this.selectList.length == 0) {
        this.$notify.warning({
          title: '警告',
          message: '请至少选择一条数据！'
        });
        return
      }
      let ids = []
      this.selectList.forEach(l => {
        ids.push(l.id)
      })
      this.$confirm('数据删除后将无法恢复，确认删除吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$api.delWaterIntake(ids).then(res => {
          if (res && res.code == 200) {
            this.$notify.success({
              title: '成功',
              message: '删除成功!'
            });
            this.listInit()
          }
        })
      }).catch(() => { });
    },
    // 多选
    handleSelectionChange(val) {
      this.selectList = val;
    },
    // size change
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`);
      this.page = 1;
      this.size = val;
      this.listInit();
    },
    // page change
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`);
      this.page = val;
      this.listInit();
    },

    areaFormatter(row, column) {
      return this.$util.searchInTree(this.areaTree, column.property, row.areaCode);
    },
    basinFormatter(row, column) {
      return this.$util.searchInTree(this.basinOptions, column.property, row.basinCode);
    },

    handleAreaCodeChange(selected){
      this.$refs.areaCodeRef.dropDownVisible = false;
      if(selected.length===0){
        this.areaChecked = []
        this.form.areaCode=0
      }
    },

    handleBasinCodeChange(selected){
      this.$refs.basinCodeRef.dropDownVisible = false;
      if(selected.length===0){
        this.basinChecked = []
        this.form.basinCode=0
      }
    },
  },
  components: { EditDialog, SingleSelectCascader }
};
</script>

<style lang="less">
.tips {
  cursor: pointer;
  margin-left: -8px;
  margin-right: 5px;
  color: #2196f3;
}
</style>
